package org.example.commerce.imp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.commerce.dao.CategoryMapper;
import org.example.commerce.dao.entity.Category;
import org.example.commerce.imp.service.CategoryService;
import org.example.common.enums.BusinessErrorCode;
import org.example.common.exception.BusinessException;
import org.example.common.response.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;



@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public R<PageInfo<Category>> getCtaegoryList(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Category> categories = categoryMapper.selectAll();
        PageInfo<Category> result = new PageInfo<>(categories);
        return R.success(result);
    }

    @Override
    public R<Category> addCategory(Category category) {
        Example example = new Example(Category.class);
        example.createCriteria().andEqualTo("name", category.getName().trim());
        if (categoryMapper.selectByExample(example).size() >= 1) {
            throw new BusinessException(BusinessErrorCode.CATEGORY_NAME_PRESENCE);
        }
        categoryMapper.insert(category);
        return R.success(category);
    }

    @Override
    public R<String> deleteCategoryById(Long id) {
        int flag = categoryMapper.deleteByPrimaryKey(id);
        if (flag == 0) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    @Override
    public R<Category> selectCategoryById(Long id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        if (category == null) {
            throw new BusinessException(BusinessErrorCode.CATEGORY_NAME_NOT_FOU);
        }
        return R.success(category);
    }

    @Override
    public R<Category> modifyCategory(Category category) {
        //id未查询到修改分类
        if (categoryMapper.selectByPrimaryKey(category.getId()) == null) {
            throw new BusinessException(BusinessErrorCode.CATEGORY_ID_NOT_FOU);
        }
        //查询是否有同名分类
        Example example = new Example(Category.class);
        example.createCriteria().andEqualTo("name", category.getName().trim());
        if (categoryMapper.selectOneByExample(example) != null) {
            throw new BusinessException(BusinessErrorCode.CATEGORY_NAME_PRESENCE);
        }
        //  复制 -> 赋值
        Category oCategory = categoryMapper.selectByPrimaryKey(category.getId());
        BeanUtils.copyProperties(category, oCategory);
        categoryMapper.updateByPrimaryKey(oCategory);
        return R.success(oCategory);
    }

}
